<template>
  <div v-loading="loading" class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">标题</label>
        <el-input v-model="query.title" clearable placeholder="标题" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" label-position="top" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="套餐设置">
            <div>
              <span>小时</span>
              <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" style="width: 150px;" />
            </div>
            <div style="margin-top: 20px;">
              <span>包月</span>
              <el-input-number v-model="form.dayPrice" :precision="2" :step="0.1" :min="0" style="width: 150px;" />
            </div>
            <div style="margin-top: 20px;">
              <span>包年</span>
              <el-input-number v-model="form.monthPrice" :precision="2" :step="0.1" :min="0" style="width: 150px;" />
            </div>
          </el-form-item>
          <el-form-item label="联系人" prop="contact">
            <el-input v-model="form.contact" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="家政图片" prop="path">
            <!-- 文件上传组件 -->
            <el-upload
              class="upload-demo"
              :limit="1"
              :action="fileUploadApi"
              :headers="headers"
              :on-preview="handlePreview"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
              :on-error="handleError"
              :file-list="fileList"
              list-type="picture-card"
            >
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500mb</div>
            </el-upload>
          </el-form-item>
          <el-form-item
            v-for="(domain, index) in domains"
            :key="domain.id"
            :label="'服务项目' + (index+1)"
          >
            <el-row :gutter="20" style="margin-bottom: 20px;">
              <el-col :span="4">
                <div class="grid-content bg-purple">
                  项目名称
                </div>
              </el-col>
              <el-col :span="8">
                <div class="grid-content bg-purple">
                  <el-input  v-model="domain.services" style="width: 300px;"/>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-bottom: 20px;">
              <el-col :span="4">
                <div class="grid-content bg-purple">
                  服务简介
                </div>
              </el-col>
              <el-col :span="8">
                <div class="grid-content bg-purple">
                  <el-input v-model="domain.briefly" :rows="3" type="textarea" style="width: 300px;"/>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col margin-left="60%">
                <div class="grid-content bg-purple">
                  <el-button type="warning" @click.prevent="removeDomain(domain)" >删除</el-button>
                </div>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button @click="addDomain">新增服务项目</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" align="center" label="标题" />
        <el-table-column align="center" label="套餐" >
          <el-table-column
            align="center"
            prop="price"
            label="小时"
            width="120">
          </el-table-column>
          <el-table-column
            align="center"
            prop="dayPrice"
            label="包月"
            width="120">
          </el-table-column>
          <el-table-column
            align="center"
            prop="monthPrice"
            label="包年"
            width="120">
          </el-table-column>
        </el-table-column>
        <el-table-column prop="content" align="center" label="内容" />
        <el-table-column prop="contact" align="center" label="联系人" />
        <el-table-column prop="phone" align="center" label="联系电话" />
        <el-table-column prop="createTime" align="center" label="创建日期" />
        <el-table-column prop="path" align="center" label="家政图片">
          <template slot-scope="{row}">
            <el-image
              :src="row.path"
              :preview-src-list="[row.path]"
              fit="contain"
              lazy
              class="el-avatar"
            >
              <div slot="error">
                <i class="el-icon-document" />
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','menageManage:edit','menageManage:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
      <el-dialog :visible.sync="dialogPictrueVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </div>
  </div>
</template>

<script>
import crudMenageManage from '@/api/system/menageManage'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'

const defaultForm = { id: null, createTime: null, updateTime: null, createBy: null, updateBy: null, deleted: null, xqId: null, price: null, dayPrice: null, monthPrice: null, title: null, content: null, contact: null, phone: null, storageId: null, path: null, fileName: null }
export default {
  name: 'MenageManage',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '家政服务数据管理', url: 'api/menageManage', idField: 'id', sort: 'id,desc', crudMethod: { ...crudMenageManage }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'menageManage:add'],
        edit: ['admin', 'menageManage:edit'],
        del: ['admin', 'menageManage:del']
      },
      rules: {
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '联系人不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '联系电话不能为空', trigger: 'blur' }
        ]
      },
      headers: { 'Authorization': getToken() },
      fileList: [],
      domains: [{
        services: '',
        briefly: '',
        id: ''
      }],
      loading: false,
      dialogImageUrl: '',
      dialogPictrueVisible: false
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.crud.optShow.download = false
      return true
    },
    // 编辑之前
    [CRUD.HOOK.beforeToEdit](obj, row) {
      this.loading = true
      crudMenageManage.detail(row.id).then(data => {
        if (data && data.datails) {
          const brieflyLis = data.datails
          const domainList = []
          for (let a = 0; a < brieflyLis.length; a++) {
            domainList.push({
              services: brieflyLis[a].services,
              briefly: brieflyLis[a].briefly,
              id: brieflyLis[a].id
            })
          }

          this.domains = domainList
        }
        this.loading = false
      })
      this.fileList.push({ url: row.path })
      return true
    },
    // 取消添加之前
    [CRUD.HOOK.beforeAddCancel]() {
      this.fileList = []
      this.domains = [{
        services: '',
        briefly: '',
        id: ''
      }]
      this.crud.form.path = ''
      this.crud.form.storageId = ''
      return true
    },
    // 取消编辑之前
    [CRUD.HOOK.beforeEditCancel]() {
      this.fileList = []
      this.domains = [{
        services: '',
        briefly: '',
        id: ''
      }]
      this.crud.form.path = ''
      this.crud.form.storageId = ''
      return true
    },
    // 提交之前
    [CRUD.HOOK.beforeSubmit]() {
      if (!this.crud.form.path || this.crud.form.path === '') {
        this.$message.error('请上传文件')
        return false
      }
      if (!this.crud.form.storageId || this.crud.form.storageId === '') {
        this.$message.error('请上传文件')
        return false
      }
      if (this.domains.length === 0) {
        this.$message.error('请填写服务项目')
        return false
      } else {
        const domains = this.domains
        for (let a = 0; a < domains.length; a++) {
          if (!domains[a].services || domains[a].services === '') {
            this.$message.error('服务项目' + (a + 1) + '请填写项目名称')
            return false
          }
          if (!domains[a].briefly || domains[a].briefly === '') {
            this.$message.error('服务项目' + (a + 1) + '请填写项目简介')
            return false
          }
        }
      }
      this.crud.form.datails = this.domains
      return true
    },
    // 提交保存之后
    [CRUD.HOOK.afterSubmit]() {
      this.fileList = []
      this.domains = [{
        services: '',
        briefly: '',
        id: ''
      }]
      this.crud.form.path = ''
      this.crud.form.storageId = ''
      return true
    },
    // 删除图片
    removePic() {
      this.crud.form.path = ''
      this.crud.form.storageId = ''
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 5mb!')
      }
      return isLt2M
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogPictrueVisible = true
    },
    handleSuccess(res, file, fileList) {
      this.crud.form.path = res.path
      this.crud.form.storageId = res.id
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.dialogVisible = false
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    removeDomain(item) {
      var index = this.domains.indexOf(item)
      if (index !== -1) {
        this.domains.splice(index, 1)
      }
    },
    addDomain() {
      if (this.domains.length === 10) {
        this.$message.error('最多添加10个项目')
        return
      }
      this.domains.push({
        briefly: '',
        services: '',
        id: ''
      })
    }
  }
}
</script>

<style scoped>

</style>
